//
//  HomeListTableViewCell.swift
//  MT
//
//  Created by M on 2019/12/13.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import SnapKit
import Kingfisher

@objc
protocol HomeListTableViewCellDelegate: NSObjectProtocol {
    
//    @objc optional func homeListCellDidTapCoverImageView(_ cell: HomeListTableViewCell)
 
    @objc optional func homeListCellDidClickPlayPauseButton(_ cell: HomeListTableViewCell, isPlay: Bool)
    
}

class HomeListTableViewCell: UITableViewCell {

    ///
    weak var delegate: HomeListTableViewCellDelegate?
    
    private lazy var authProvider: MTProvider<DDCAuthAPI> = {
        let provider = MTProvider<DDCAuthAPI>()
        return provider
    }()
    
    /// 展示模型
    var model: HomeListDetailModel? {
        didSet {
            guard let model = model else { return }
            /// 封面图
            if let urlString = model.imgs?.first?.href {
                coverImageView.kf.setImage(with: URL(string: urlString), placeholder: UIImage(named: "placeholder-rectangle"))
            }
            /// 用户名
            userNameButton.setTitle("@ \(model.nickname ?? "")", for: .normal)
            /// 用户信息 Label
            userInfoLabel.text = "\(model.age ?? 0)岁  \(model.area ?? "")"
            
            headerImageView.kf.setImage(with: URL(string: model.headerUrl ?? ""))
            
            pauseIconButton.isHidden = !model.isContainVideo
            
            goodButton.setupLikeCount("1000")
            goodButton.setupLikeState(true)
            
            if model.giftPrice > 0 {
                giftContainerView.isHidden = false
                let text = "收到\(model.giftPrice)点券"
                flowerGiftLabel.text = text
            } else {
                giftContainerView.isHidden = true
            }
            
            addFriendButton.isHidden = model.isFriend
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initializeUI()
        makeConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 封面图
    lazy var coverImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.tag = 8800
        imgView.contentMode = .scaleAspectFill
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(homeListCell(didTapCoverImageView:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    /// 视频暂停 / 开始按钮
    lazy var pauseIconButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "icon_start"), for: .normal)
        btn.setImage(UIImage(named: "icon_stop-1"), for: .selected)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickPlayPauseButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 用户名按钮
    lazy var userNameButton: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickUserIconButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 是否在线
    lazy var onlineStatusLabelLeft: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(12)
        label.textColor = UIColor(hex: 0xffc000)
        label.backgroundColor = UIColor(hex:0x000000).withAlphaComponent(0.5)
        label.text = "15分钟前在线"
        label.textAlignment = .center
        return label
    }()
    
    /// 下划线 View
    lazy var underlineView: UIView = {
        let view = UIView()
        view.backgroundColor = MainYellowColor
        view.layer.cornerRadius = 1.5
        return view
    }()
    
    /// 用户信息 Label
    lazy var userInfoLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCMediumFont(12)
        label.textColor = .white
        return label
    }()
    
    /// 头像
    lazy var headerImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        imgView.isUserInteractionEnabled = true
        imgView.layer.cornerRadius = 22
        imgView.clipsToBounds = true
        return imgView
    }()
    
    /// 加好友按钮
    lazy var addFriendButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "icon_addFriend"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickAddFriendButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 举报按钮
    lazy var reportButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("举报", for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.theme.main, for: .normal)
        btn.layer.cornerRadius = 12
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.theme.main.cgColor
        btn.layer.masksToBounds = true
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickReportButtonButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 屏蔽按钮
    lazy var momentButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("屏蔽", for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.theme.main, for: .normal)
        btn.layer.cornerRadius = 12
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.theme.main.cgColor
        btn.layer.masksToBounds = true
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickMomentButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 送礼物按钮
    lazy var sendGiftButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "icon_sendGift"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(homeListCell(didClickSendGiftButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 点赞
    lazy var goodButton: GKLikeView = {
        let btn = GKLikeView()
        return btn
    }()
    
    /// GiftContainer
    lazy var giftContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x161616).withAlphaComponent(0.67)
        view.layer.cornerRadius = 11
        view.isHidden = true
        return view
    }()
    
    /// 花 icon
    lazy var flowerIconImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "icon_gift_display")
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    /// 花 Label
    lazy var flowerGiftLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(11)
        label.textColor = .white
        label.textAlignment = .left
        return label
    }()
    
}

// MARK: ------------------ Overrides ----------------------
extension HomeListTableViewCell {
    
    override func prepareForReuse() {
        pauseIconButton.isSelected = false
        coverImageView.image = nil
        userNameButton.setTitle(nil, for: .normal)
        userInfoLabel.text = nil
        giftContainerView.isHidden = true
    }
    
}

// MARK: ------------------ Initialize ----------------------
extension HomeListTableViewCell {
    
    /// UI 初始化
    private func initializeUI() {
        contentView.backgroundColor = UIColor(hex:0x000000)
        selectionStyle = .none
        
        contentView.addSubview(coverImageView)
//        contentView.addSubview(pauseIconButton)
//        contentView.addSubview(userNameButton)
//        contentView.addSubview(underlineView)
//        contentView.addSubview(userInfoLabel)
//        contentView.addSubview(addFriendButton)
//        contentView.addSubview(sendGiftButton)
        coverImageView.addSubview(giftContainerView)
        coverImageView.addSubview(userNameButton)
        coverImageView.addSubview(onlineStatusLabelLeft)
        coverImageView.addSubview(userInfoLabel)
        coverImageView.addSubview(headerImageView)
        coverImageView.addSubview(addFriendButton)
        coverImageView.addSubview(goodButton)
//        giftContainerView.addSubview(flowerIconImgView)
//        giftContainerView.addSubview(flowerGiftLabel)
    }
    
    /// 约束
    private func makeConstraints() {

//        sendGiftButton.snp.makeConstraints { (make) in
//            make.right.equalTo(contentView).offset(-16)
//            make.bottom.equalTo(contentView).offset(-26)
//            make.width.equalTo(70)
//            make.height.equalTo(26)
//        }
//
//        addFriendButton.snp.makeConstraints { (make) in
//            make.right.equalTo(sendGiftButton)
//            make.bottom.equalTo(sendGiftButton.snp.top).offset(-9)
//            make.width.equalTo(70)
//            make.height.equalTo(26)
//        }
        
//        underlineView.snp.makeConstraints { (make) in
//            make.left.equalTo(userNameButton)
//            make.top.equalTo(userNameButton.snp.bottom).offset(4)
//            make.width.equalTo(14)
//            make.height.equalTo(3)
//        }
        
        
        coverImageView.snp.makeConstraints { (make) in
            make.left.top.right.bottom.equalToSuperview()
        }
        
        onlineStatusLabelLeft.snp.makeConstraints { (make) in
            make.left.equalTo(contentView).offset(10)
            make.bottom.equalTo(contentView).offset(-TabBarHeight-68)
            make.width.equalTo(80)
        }
        
        userNameButton.snp.makeConstraints { (make) in
            make.left.equalTo(contentView).offset(10)
            make.bottom.equalTo(contentView).offset(-TabBarHeight-ScreenBottomExtraOffset-35)
        }
        
        userInfoLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNameButton)
            make.top.equalTo(userNameButton.snp.bottom)
        }
        
        headerImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.right.equalTo(-10)
            make.bottom.equalTo(contentView).offset((-TabBarHeight-220))
        }
        
        addFriendButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(headerImageView)
            make.top.equalTo(headerImageView.snp.bottom).offset(-8)
            make.width.height.equalTo(16)
        }
        
        goodButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(addFriendButton)
            make.top.equalTo(addFriendButton.snp.bottom).offset(15)
            make.width.equalTo(36)
            make.height.equalTo(31)
        }
//        pauseIconButton.snp.makeConstraints { (make) in
//            make.right.bottom.equalTo(coverImageView).offset(-12)
//            make.width.height.equalTo(55)
//        }
//        
//        giftContainerView.snp.makeConstraints { (make) in
//            make.left.equalTo(coverImageView).offset(-11)
//            make.bottom.equalTo(coverImageView).offset(-13)
//            make.height.equalTo(22)
//        }
//        
//        flowerIconImgView.snp.makeConstraints { (make) in
//            make.left.equalTo(giftContainerView).offset(15)
//            make.width.height.equalTo(18)
//            make.centerY.equalTo(giftContainerView)
//        }
//        
//        flowerGiftLabel.snp.makeConstraints { (make) in
//            make.left.equalTo(flowerIconImgView.snp.right).offset(4)
//            make.right.equalTo(giftContainerView).offset(-6)
//            make.centerY.equalTo(giftContainerView)
//        }
//        
//        if UserDefaults.AppValidate.isValidate.storedBool {
//            
//            contentView.addSubview(reportButton)
//            contentView.addSubview(momentButton)
//            
//            reportButton.snp.makeConstraints { (make) in
//                make.right.equalTo(addFriendButton).offset(-3)
//                make.bottom.equalTo(addFriendButton.snp.top).offset(-9)
//                make.width.equalTo(65)
//                make.height.equalTo(24)
//            }
//            
//            momentButton.snp.makeConstraints { (make) in
//                make.right.equalTo(addFriendButton).offset(-3)
//                make.bottom.equalTo(reportButton.snp.top).offset(-9)
//                make.width.equalTo(65)
//                make.height.equalTo(24)
//            }
//            
//        }
        
    }
    
}

// MARK: ------------------ 点击方法 ----------------------
@objc
extension HomeListTableViewCell {
    
    /// 点击播放按钮
    private func homeListCell(didClickPlayPauseButton sender: UIButton) {
        if !(model?.isContainVideo ?? false) {
            return
        }
        sender.isSelected = !sender.isSelected
        if let delegate = delegate {
            delegate.homeListCellDidClickPlayPauseButton?(self, isPlay: !sender.isSelected)
        }
    }

    /// 点击用户按钮
    private func homeListCell(didClickUserIconButton sender: UIButton) {
        var dict: [String:Any]?
        if let userName = model?.userName {
            dict = ["username" : userName]
        }
        NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionUserInfo.name, object: nil, userInfo: dict)
    }
    
    /// 屏蔽信息流按钮
    private func homeListCell(didClickMomentButton sender: UIButton) {
        // 取消按钮 index = 0
        let clickedHandler = { (sheetView: MTActionSheetView, index: Int) in
            if index == 0 {
                return
            }
            if index == 1 {
                var dict: [String:Any]?
                if let userName = self.model?.userName, let id = self.model?.id {
                    dict = ["imUserName" : userName, "id" : id]
                }
                NotificationCenter.default.post(name: GlobalNotificationName.moment.name, object: nil, userInfo: dict)
            }
        }
        
        let otherButtonTitles = ["屏蔽此人"]
        let actionSheet = MTActionSheetView(cancelButtonTitle: "取消",
                                          otherButtonTitles: otherButtonTitles,
                                          clickedHandler: clickedHandler)
        actionSheet.canTouchToDismiss = true
        actionSheet.show()
    }
    
    /// 点击加好友按钮
    private func homeListCell(didClickAddFriendButton sender: UIButton) {
        /// 极光用户名
//        guard let username = model?.userName else { return }
        guard let model = model, let username = model.userName else { return }
        
        let vc = MTAddFriendViewController()
        vc.userName = username
        vc.nickName = model.nickname
        
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
//
//        let currentUser = JMSGUser.myInfo()
//        if currentUser.username.isEmpty {
//            NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: nil)
//            return
//        }
//        let info = JCVerificationInfo.create(username: username, nickname: model.nickname, appkey: currentUser.appKey!, resaon: "", state: JCVerificationType.wait.rawValue, initiator: currentUser.username)
//        JCVerificationInfoDB.shareInstance.insertData(info)
//
//        JMSGFriendManager.sendInvitationRequest(withUsername: username, appKey: nil, reason: "我是\(JMSGUser.myInfo().nickname ?? "")") { (result, error) in
//            let dict: [String: Any] = ["isSuccess": error == nil]
//            NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: dict)
//        }
    }
    
    /// 点击送礼物按钮
    private func homeListCell(didClickSendGiftButton sender: UIButton) {
        var dict: [String:Any]?
        if let userName = model?.userName {
            dict = ["imUserName" : userName, "isFriend" : model?.isFriend ?? false]
        }
        NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionSendGift.name, object: nil, userInfo: dict)
    }
    
    private func homeListCell(didClickReportButtonButton sender: UIButton) {
        // 取消按钮 index = 0
        let clickedHandler = { (sheetView: MTActionSheetView, index: Int) in
            if index == 0 {
                return
            }
            self.report()
        }
        
        let otherButtonTitles = ["垃圾广告", "违法信息", "淫秽色情", "其他"]
        let actionSheet = MTActionSheetView(cancelButtonTitle: "取消",
                                          otherButtonTitles: otherButtonTitles,
                                          clickedHandler: clickedHandler)
        actionSheet.canTouchToDismiss = true
        actionSheet.show()
    }
    
    /// 举报用户的接口
    private func report() {
        
        if let un = self.model?.userName {
            MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "正在上报, 请稍后")
            authProvider.originRequest(.report(username: un), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "感谢您的反馈, 系统将在24小时内处理")
                    } else {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    }
                    DispatchQueue.main.after(2) {
                        MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                    }
                    break
                case .failure(_):
                    MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    DispatchQueue.main.after(1) {
                        
                        DispatchQueue.main.after(2) {
                            MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                        }
                    }
                    break
                }
                
            }
        }
        
    }
    
    /// 点击封面图
    private func homeListCell(didTapCoverImageView gestureRecognizer: UITapGestureRecognizer) {
        var dict: [String:Any]?
        if let userName = model?.userName {
            dict = ["username" : userName]
        }
        NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionUserInfo.name, object: nil, userInfo: dict)
    }
    
}

